package com.mxy.myapplication2.kotlin

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.mxy.myapplication2.R
import com.mxy.myapplication2.java.Util
import com.mxy.myapplication2.service.SocketServer
import com.mxy.myapplication2.util.IsWebCanBeUse
import kotlinx.android.synthetic.main.activity_socket_server.*

/**
 * 基于TCP的Socket通信_server端
 */
class SocketServerActivity : AppCompatActivity(), View.OnClickListener {


    //以后台服务的形式启动socketserver
    private val serverIntent: Intent by lazy {
        Intent(this, SocketServer::class.java)
    }
    //记录服务器状态值以及客户端发送过来的消息
    private val informations: ArrayList<String> = ArrayList()
    private lateinit var adapter: AdapterForSocketServerInformationList
    private val linearLayoutManager by lazy {
        LinearLayoutManager(this)
    }
    private val newContentReceiver: NewContentReceiver = NewContentReceiver()
    private val wifiChangeReceiver: WifiChangeReceiver = WifiChangeReceiver()

    companion object {
        private val serverClassName = "com.mxy.myapplication2.service.SocketServer"
        val newContentReceiverAction = "newMessageServer"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_socket_server)
        initView()


        //监听WIFI连接情况
        val filter = IntentFilter()
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION)
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        registerReceiver(wifiChangeReceiver, filter)

        val intentFilter = IntentFilter()
        intentFilter.addAction(newContentReceiverAction)
        registerReceiver(newContentReceiver, intentFilter)

    }


    fun initView() {

        this.ipAddress.setText("本机IP : " + Util.getIpAddress())

        this.startServer.setOnClickListener(this)
        this.shutdownServer.setOnClickListener(this)

        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        this.messageList.layoutManager = linearLayoutManager
        adapter = AdapterForSocketServerInformationList(this, informations)
        this.messageList.adapter = adapter
    }

    /**
     * 启动socket服务器
     * */
    fun startServerSocket() {

        if (Util.isServiceExisted(this, serverClassName)) {
            Util.showToast(this, "Socket服务已启动")
        } else {
            if (!IsWebCanBeUse.isWIFIConnection(this)) {
                Util.showToast(this, "请将设备连接至WIFI")
                return
            }
            if (Util.getIpAddress() == null || Util.getIpAddress().equals("")) {
                Util.showToast(this, "当前服务器暂无IP地址")
                return
            }
            startService(serverIntent)
            addNewInformation("启动Socket服务")
        }

    }

    /**
     * 关闭socket服务器
     * */
    fun shutDownServerSocket() {

        if (Util.isServiceExisted(this, serverClassName)) {
            stopService(serverIntent)
            addNewInformation("关闭Socket服务")
            adapter.notifyDataSetChanged()
        } else {
            Util.showToast(this, "Socket服务未启动")
        }

    }


    /**
     * 记录操作日志和从客户端发来的消息并刷新列表
     * */
    fun addNewInformation(content: String) {
        if (!"".equals(content)) {
            informations.add(content)
            adapter.notifyDataSetChanged()
            linearLayoutManager.scrollToPosition(informations.size - 1)
        }
    }


    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.startServer -> {
                startServerSocket()
            }
            R.id.shutdownServer -> {
                shutDownServerSocket()
            }
        }
    }

    inner class WifiChangeReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            ipAddress.setText("本机IP : " + Util.getIpAddress())
        }
    }

    inner class NewContentReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent!!.action.equals(newContentReceiverAction)) {
                if (intent.getStringExtra(newContentReceiverAction) != null) {
                    addNewInformation(intent.getStringExtra(newContentReceiverAction))
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        stopService(serverIntent)
        unregisterReceiver(newContentReceiver)
        unregisterReceiver(wifiChangeReceiver)
    }
}